package org.lex.ftp.ui.speed;

import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import org.lex.filter.Filter;
import org.lex.ftp.ui.find.old.speed.SearchResult;
import org.lex.net.ftp.FTPURL;


public class TestThread implements Runnable {
	private FileFinder fileFinder = null;
	private Filter filter = null;
	FTPURL url = null;
	// ===========================
	int id = -1;
	ServerStatus status = null;
	long speed = 0L;
	// =================================
	private ChangeListener listener = null; // support callback

	public TestThread(Filter target, FTPURL ftpUrl, int index) {
		super();
		this.filter = target;
		this.url = ftpUrl;
		this.id = index;
		this.fileFinder = new FileFinder(ftpUrl);
	}

	public SearchResult getSearchResult() {
		return fileFinder.getResult();
	}

	public ServerStatus getServerStatus() {
		return status;
	}

	public void setChangeListener(ChangeListener listener) {
		this.listener = listener;
	}

	public void run() {
		// test if server can be opened
		if (false == fileFinder.open()) {
			fireStateChanged(ServerStatus.ConnectFailed);
			fileFinder.cleanup();
			return;
		}
		// server opened, test if specified file exist
		if (false == fileFinder.exist(filter)) {
			fireStateChanged(ServerStatus.NoSuchFile);
			fileFinder.cleanup();
			return;
		} else {
			fireStateChanged(ServerStatus.Found);
		}
		// specified file exists, test download speed
		this.speed = fileFinder.speed();
		fireStateChanged(ServerStatus.Found);
		// finished, clean up
		fileFinder.cleanup();
		return;
	}

	private void fireStateChanged(ServerStatus newStatus) {
		this.status = newStatus;
		this.listener.stateChanged(new ChangeEvent(this));
	}
}
